#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //初始值
    ui->portEdit->setText("9999");
    this->setWindowTitle("服务器");
    //状态栏
    statusLabel = new QLabel;
    statusLabel->setPixmap(QPixmap(":/res/linkN.png").scaled(20, 20));
    QLabel *textLabel = new QLabel;
    textLabel->setText("连接状态");
    ui->statusbar->addWidget(textLabel);
    ui->statusbar->addWidget(statusLabel);

    //1.创建服务器对象
    server = new QTcpServer(this);

    //启动服务器按钮
    connect(ui->startServerBtn, &QPushButton::clicked, this, [=](){
        if(ui->portEdit->text() == ""){
            qDebug() << "空";
            QMessageBox::warning(this, "警告", "端口不能为空");
        }else{
            qDebug() << "有东西";
            //字符串转qint16(ushort)
            qint16 port = ui->portEdit->text().toUShort();

            //2.启动监听
            this->server->listen(QHostAddress::Any, port);

            //设置启动按钮不可用
            ui->startServerBtn->setDisabled(true);
        }
    });

    //3.监听服务器 新的连接
    connect(this->server, &QTcpServer::newConnection, [=](){
        //4.获取客户端连接成功的 QTcpSocket
        this->socket = this->server->nextPendingConnection();
        ui->recordBox->append("---客户端连接成功---");
        statusLabel->setPixmap(QPixmap(":/res/linkY.png").scaled(20, 20));
        this->statusLabel->setPixmap(QPixmap(":/res/linkY.png").scaled(20, 20));

        //监听 接收的数据
        connect(socket, &QTcpSocket::readyRead, [=](){
            QByteArray data = socket->readAll();
            ui->recordBox->append("客户端说：" + data);
        });

        //监听客户端断开的信号
        connect(this->socket, &QTcpSocket::disconnected, [=](){
            statusLabel->setPixmap(QPixmap(":/res/linkN.png").scaled(20, 20));
            QMessageBox::warning(this, "客户端", "客户端断开连接！");
            ui->recordBox->append("---客户端断开连接---");

            //释放内存
            socket->close();
            socket->deleteLater();  //delete socket;
        });
    });

    //5.使用连接客户端成功返回的QTcpSocket和客户端进行通信
    connect(ui->sendMsgBtn, &QPushButton::clicked, [=](){
        QString msg = ui->msgBox->toPlainText();
        if(msg == ""){
            QMessageBox::warning(this, "警告", "发送的数据为空!");
        }else{
            ui->recordBox->append("服务器说：" + msg);
            //发送消息
            this->socket->write(msg.toUtf8());
            ui->msgBox->setPlainText("");
        }
    });


}






MainWindow::~MainWindow()
{
    delete ui;
}
